import { getjwtdata } from '../utils/getWebAjax'
import ApiError from '../error/ApiError'
import ApiErrorNames from '../error/ApiErrorNames'
import AiUser from '../model/AiUser'

const cheackAiUser = () => {
    return async (ctx, next) => {
        let url = ctx.request.url
        // 需要验证
        let cheackUrls = [
            /\/api\/aiuser\/*/,
            /\/api\/dlyuser\/*/,
            /\/api\/ai\/*/,
            /\/api\/zhangfuai\/*/,
            /\/api\/alipay\/*/,
            // /\/api\/alipay\/orderRecords/,
            // /api/alipay/cb
        ]
        // 需要验证中的需要跳过
        let jumpUrls = [
            /\/api\/aiuser\/code/,
            /\/api\/aiuser\/creted/,
            /\/api\/dlyuser\/code/,
            /\/api\/dlyuser\/creted/,
            /\/api\/dlyuser\/bindinfo/,
            /\/api\/zhangfuai\/aiRspRs/,
            /\/api\/zhangfuai\/priceConfigList/,
            /\/api\/alipay\/cb/,
            /\/api\/aiuser\/refreshLogin/,
        ]
        if (cheackUrls.some(item => item.test(url))) {
            if (jumpUrls.some(item => item.test(url))) {
                return await next()
            }
            const getArt = await refoMackAiUerData(ctx).catch(err => {
                // console.log('err', err)
                throw new ApiError(ApiErrorNames.selectInDengtData(err))
            })
            ctx.request.header.jwtuserinfo = JSON.stringify(getArt)
            return await next()

        }
        return await next()
    }
}

module.exports = cheackAiUser

async function refoMackAiUerData(ctx) {
    const getJwtData = await getjwtdata(ctx)
    console.log('getJwtData', getJwtData)
    if (!getJwtData.jwtdata) {
        return Promise.reject('需要验证的接口')
    }
    if (getJwtData.jwtdata.for && getJwtData.jwtdata.for === "dy-shop") {
        return getJwtData
    }
    if (!getJwtData.jwtdata.for || (getJwtData.jwtdata.for !== 'ai' && getJwtData.jwtdata.for !== 'dy')) {
        return Promise.reject('非体系登陆用户')
    }
    const getUserData = await AiUser.findOne({
        phone: getJwtData.jwtdata.phone
    })

    if (!getUserData) {
        return Promise.reject('用户不存在， 请先注册登陆')
    }
    return getUserData
}